﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileStorage.Caching;

namespace FileStorage.Comparing
{
    public static class FileStorageCompareFacade
    {
        public static Dictionary<Guid, List<Guid>> GetDuplicates(string fileStorageName, IDataIdentifierComparer dataIdentifierComparer, ICacheContainer cacheContainer)
        {
            Dictionary<Guid, List<Guid>> result = new Dictionary<Guid, List<Guid>>();

            Dictionary<Guid, Guid> dataIdentifierToHash = new Dictionary<Guid, Guid>();
            List<Guid> allIndexes = FileStorageCacherFacade.GetAllDataIdentifiersBasedUponFileStorageIndexFile(fileStorageName, cacheContainer);
            //
            // loop over all items, and calculate the hashes based upon the specified IDataIdentifierComparer
            //
            foreach (Guid currentDataIdentifier in allIndexes)
            {
                dataIdentifierToHash[currentDataIdentifier] = dataIdentifierComparer.GetHash(fileStorageName, cacheContainer, currentDataIdentifier);
            }
            //
            // loop over each item, and locate the ones that have a match according to the specified IDataIdentifierComparer
            //
            foreach (Guid currentDataIdentifier in allIndexes)
            {
                Guid currentHash = dataIdentifierToHash[currentDataIdentifier];
                List<Guid> matchingOtherDataIdentifiers = 
                        (from identicalDataIdentifier in dataIdentifierToHash.Keys
                         where dataIdentifierToHash[identicalDataIdentifier] == currentHash && identicalDataIdentifier != currentDataIdentifier
                         select identicalDataIdentifier).ToList();
                result.Add(currentDataIdentifier, matchingOtherDataIdentifiers);
            }

            

            return result;
        }
    }
}
